// Reference models.
const {as4KDotsUser} = require("../db/init");
// JWT facade.
const JWT = require('#facades/jwt.facade');
// Password hash and compare service.
const bcrypt = require('#services/bcrypt.service');
// Custom error.
const {Err} = require('#factories/errors');
const redis = require('../utils/redis');

module.exports = {
    // Auth:
    _register,
    login,
    // Auth\

    // Private:
    _getFullName

    // Add your methods here...

    // Private\
}

// Auth:
async function _register({email, password}) {
    try {
        // Try to create new user.
        const user = await as4KDotsUser.create({
            email,
            password
        });

        // Issue new access and refresh JWT.
        const [tokens] = await JWT.issueTokens({user});

        // Prepare output.
        const result = [
            tokens,
            user
        ];
        // Send output.
        return Promise.resolve(result);
    } catch (error) {
        return Promise.reject(error);
    }
}

async function login({phone, code}) {
    try {
        console.log({phone, code})
        // Try to find user.
        let user = await as4KDotsUser.findOne({
            where: {
                phone: phone,
                // password: password,
            }
        });

        if (!user) {
            // If no such user was found, throw error with name UserNotFound:
            // const err = new Err('as4KDotsUser not found');
            // err.name = "UserNotFound";
            user = await as4KDotsUser.create({
                phone: phone
            })
        }
        //
        // if (!bcrypt.comparePasswords(code, user.password)) {
        //     // Validation failed,
        //     // throw custom error with name Unauthorized:
        //     const err = new Err(`Validation failed.`);
        //     err.name = "ValidationError";
        //     throw err;
        // }

        const r_code = await redis.get(`login_code_${phone}`)
        if (r_code === '' || r_code === undefined) {
            const err = new Err(`Validation failed.`);
            err.name = "ValidationError";
            throw err;
        }
        // Issue new access and refresh JWT.
        const [tokens] = await JWT.issueTokens({user});

        // Prepare output.
        const result = [
            tokens,
            user
        ];
        // Send output.
        return Promise.resolve(result);
    } catch (error) {
        return Promise.reject(error);
    }
}

// Auth\

// Private:
async function _getFullName({userId}) {
    try {
        // Try to find user.
        const user = await as4KDotsUser.findById(userId);

        if (!user) {
            // If no such user was found, throw error with name UserNotFound:
            const err = new Err('as4KDotsUser not found');
            err.name = "UserNotFound";
            throw err;
        }

        // Get value of virtual field 'fullName'.
        const fullName = user.fullName;

        // Send output.
        return Promise.resolve([fullName]);
    } catch (error) {
        return Promise.reject(error);
    }
}

module.exports.isVip1 = async function (user_id) {
    const isVip = false;
    return isVip;
}
// Private\
